from PySide6.QtWidgets import QApplication
import os
from PySide6.QtCore import Qt

from src.config import app_config

THEMES_DIR = "themes"

def get_available_themes():
    """Scan the themes directory and return a list of available theme names."""
    if not os.path.exists(THEMES_DIR):
        return []
    themes = [
        os.path.splitext(f)[0]
        for f in os.listdir(THEMES_DIR)
        if f.endswith(".qss")
    ]
    return sorted(themes)

def load_stylesheet(theme_name):
    """Load the stylesheet content from a .qss file."""
    file_path = os.path.join(THEMES_DIR, f"{theme_name}.qss")
    if not os.path.exists(file_path):
        print(f"Warning: Theme file not found at {file_path}")
        return ""
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            return f.read()
    except Exception as e:
        print(f"Error loading theme file {file_path}: {e}")
        return ""

def is_dark_mode():
    """Check if the system is in dark mode using Qt's style hints."""
    app = QApplication.instance()
    if not app:
        return False
    return app.styleHints().colorScheme() == Qt.ColorScheme.Dark

def apply_theme(theme_name):
    """Apply the specified theme to the application."""
    app = QApplication.instance()
    if not app:
        return

    stylesheet = ""
    if theme_name == "auto":
        if is_dark_mode():
            stylesheet = load_stylesheet("dark")
        else:
            stylesheet = load_stylesheet("light")
    else:
        stylesheet = load_stylesheet(theme_name)

    if stylesheet:
        app.setStyleSheet(stylesheet)


def get_current_theme():
    """Get the currently saved theme from the application config."""
    return app_config.get("ui.theme", "auto")


def set_theme(theme_name):
    """Save the selected theme to the config and apply it."""
    app_config.set("ui.theme", theme_name, emit_signal=False)
    try:
        app_config.save()
    except Exception as e:
        print(f"Error saving theme to config: {e}")
    apply_theme(theme_name)